﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer.NewUi
{
    public partial class AddCompanyGroupForm : BaseForm
    {
        #region Form Constructor
        private List<CompanyGroupResult> _companyGroupResults;
        public List<CompanyGroupResult> ChooseCompanyGroup { get; set; }
        private UserService _userService;
        private static object lockWait = new object();
        private LoadingWaitForm _loadingWaitForm;
        public AddCompanyGroupForm()
        {
            InitializeComponent();
            _userService = new UserService();
            ChooseCompanyGroup = new List<CompanyGroupResult>();
        }
        #endregion

        #region Button Confirm Event
        private void Btn_Confirm_Click(object sender, EventArgs e)
        {
            foreach (TreeNode treeNode in tv_CompanyGroup.Nodes)
                GetCheckNode(treeNode);
            Close();
        }

        private void GetCheckNode(TreeNode node)
        {
            if (node.Checked)
                ChooseCompanyGroup.Add(node.Tag as CompanyGroupResult);
            if (node.Nodes.Count > 0)
                foreach (TreeNode subNode in node.Nodes)
                {
                    GetCheckNode(subNode);
                }
        }
        #endregion

        #region Form Event
        private void AddCompanyGroupForm_Shown(object sender, EventArgs e)
        {
            _companyGroupResults =
     CacheGlobal.GetCache(GlobalString.System_Config_String.CompanyGroupCollectionCache) as List<CompanyGroupResult>;
            if (null == _companyGroupResults)
            {
                SetCacheData();
                _companyGroupResults =
      CacheGlobal.GetCache(GlobalString.System_Config_String.CompanyGroupCollectionCache) as List<CompanyGroupResult>;
            }
            else
            {
                var companyGroupRoot = _companyGroupResults.Where(x => x.Pidk__BackingField == 0).ToList();
                foreach (var companyGroupResult in companyGroupRoot)
                {
                    var rootNode = new TreeNode
                    {
                        Text = companyGroupResult.Namek__BackingField,
                        Tag = companyGroupResult
                    };
                    var subItemCollection = FindCompanyGroupSubItem(companyGroupResult.GroupIdk__BackingField);
                    foreach (var treeNode in subItemCollection)
                        rootNode.Nodes.Add(treeNode);
                    tv_CompanyGroup.Nodes.Add(rootNode);
                }
            }
        }

        private void SetCacheData()
        {
            try
            {
                lock (lockWait)
                {
                    _loadingWaitForm = new LoadingWaitForm();
                    _loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                    _loadingWaitForm.SetDescription(GlobalString.System_Config_String.GetCompanyGroupAndUserGroup);
                    _loadingWaitForm.StartPosition = FormStartPosition.CenterScreen;
                }
                var backgroundWorkerGetCompanyInfo = new BackgroundWorker();
                backgroundWorkerGetCompanyInfo.DoWork += backgroundWorkerGetCompanyInfo_DoWork;
                backgroundWorkerGetCompanyInfo.RunWorkerAsync();
                _loadingWaitForm.ShowDialog();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("SetCacheData has problem", ex);
                XtraMessageBox.Show("获取组织机构公共组失败，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
            }
        }

        void backgroundWorkerGetCompanyInfo_DoWork(object sender, DoWorkEventArgs e)
        {
            var result = _userService.GetCompanyGroupAndUserGroup();
            CacheGlobal.Add(GlobalString.System_Config_String.AllCompanyCollectionCache, result.CompanyResultsk__BackingField.ToList());
            CacheGlobal.Add(GlobalString.System_Config_String.CompanyGroupCollectionCache, result.CompanyGroupResultsk__BackingField.ToList());
            CacheGlobal.Add(GlobalString.System_Config_String.UserGroupCollectionCache, result.UserGroupResultsk__BackingField.ToList());
            if (!IsHandleCreated)
                CreateHandle();
            Invoke((EventHandler)delegate
            {
                _loadingWaitForm.Close();
                _companyGroupResults =
           CacheGlobal.GetCache(GlobalString.System_Config_String.CompanyGroupCollectionCache) as List<CompanyGroupResult>;
                var companyGroupRoot = _companyGroupResults.Where(x => x.Pidk__BackingField == 0).ToList();
                foreach (var companyGroupResult in companyGroupRoot)
                {
                    var rootNode = new TreeNode
                    {
                        Text = companyGroupResult.Namek__BackingField,
                        Tag = companyGroupResult
                    };
                    var subItemCollection = FindCompanyGroupSubItem(companyGroupResult.GroupIdk__BackingField);
                    foreach (var treeNode in subItemCollection)
                        rootNode.Nodes.Add(treeNode);
                    tv_CompanyGroup.Nodes.Add(rootNode);
                }
            });
        }

        private IEnumerable<TreeNode> FindCompanyGroupSubItem(int groupId)
        {
            var result = new List<TreeNode>();
            var subCompanyGroup = _companyGroupResults.Where(x => x.Pidk__BackingField == groupId);
            foreach (var companyGroupResult in subCompanyGroup)
            {
                var subItem = new TreeNode
                {
                    Text = companyGroupResult.Namek__BackingField,
                    Tag = companyGroupResult
                };
                var subSubItemCollection = FindCompanyGroupSubItem(companyGroupResult.GroupIdk__BackingField);
                foreach (var treeNode in subSubItemCollection)
                    subItem.Nodes.Add(treeNode);
                result.Add(subItem);
            }
            return result;
        }
        #endregion
    }
}